package com.seguriapp.entitieslist.gwt.server;

import static com.google.common.collect.Lists.newArrayList;

import java.util.List;

import net.customware.gwt.dispatch.server.ExecutionContext;
import net.customware.gwt.dispatch.shared.DispatchException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.restlet.data.MediaType;
import org.restlet.resource.ClientResource;

import com.seguriapp.common.config.GlobalConfigLoader;
import com.seguriapp.common.gwt.server.AbstractSeguriAppHandler;
import com.seguriapp.entities.District;
import com.seguriapp.entitieslist.gwt.shared.GetDistrictsListAction;
import com.seguriapp.entitieslist.gwt.shared.GetDistrictsListResult;

public class GetDistrictsListHandler extends AbstractSeguriAppHandler<GetDistrictsListAction, GetDistrictsListResult> {

  private static final Logger LOGGER = Logger.getLogger(GetDistrictsListHandler.class);

  public Class<GetDistrictsListAction> getActionType() {
    return GetDistrictsListAction.class;
  }

  public GetDistrictsListResult execute(GetDistrictsListAction action, ExecutionContext context) throws DispatchException {

    final GetDistrictsListResult result = new GetDistrictsListResult();
    try {
      final String serverUrl = GlobalConfigLoader.getInstance().getGlobalConfig().getBackEndUrl();
      final String url = serverUrl.concat(GlobalConfigLoader.getInstance().getGlobalConfig().getDistrictsList());
      final ClientResource resource = new ClientResource(String.format(url, 127));
      final String districtListJs = resource.get(MediaType.TEXT_PLAIN).getText();
      LOGGER.info("Data received : \n" + districtListJs);
      result.setDistrictsList(getJsonDataFromString(districtListJs));
    } catch (Exception e) {
      LOGGER.error("Error obtaining the initial data \n", e);
    }
    return result;
  }

  private List<District> getJsonDataFromString(final String districtsListJs) {
    final List<District> districtsList = newArrayList();
    final JSONObject root = JSONObject.fromObject(districtsListJs);
    JSONArray dataArray = null;
    JSONObject jo = null;
    if (root.has("districtsList")) {
      dataArray = root.getJSONArray("districtsList");
      if (dataArray != null) {
        for (int i = 0; i < dataArray.size(); i++) {
          jo = dataArray.getJSONObject(i);
          final District district = processjSONObject(jo);
          if (district != null){
            districtsList.add(district);
          }
        }
      }
    }
    return districtsList;
  }

  private District processjSONObject(final JSONObject jo) {
    if (jo.has("id") && jo.has("name")) {
      final District district = new District();
      district.setId(jo.getLong("id"));
      district.setName(jo.getString("name"));
      return district;
    }
    return null;
  }

}
